﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace SampleApplication2.Commands
{
  /// <summary>
  /// A Command for use with events - Passes the eventargs as a parameter (Usefull in Closing etc events that may be cancelled)
  /// </summary>
  public class InteractiveCommand : TriggerAction<DependencyObject>
  {
    protected override void Invoke(object parameter)
    {
      if (base.AssociatedObject != null)
      {
        ICommand command = this.ResolveCommand();
        if ((command != null) && command.CanExecute(parameter))
        {
          command.Execute(parameter);
        }
      }
    }

    private ICommand ResolveCommand()
    {
      ICommand command = null;
      if (this.Command != null)
      {
        return this.Command;
      }
      if (base.AssociatedObject != null)
      {
        foreach (PropertyInfo info in base.AssociatedObject.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
        {
          if (typeof(ICommand).IsAssignableFrom(info.PropertyType) && string.Equals(info.Name, this.CommandName, StringComparison.Ordinal))
          {
            command = (ICommand)info.GetValue(base.AssociatedObject, null);
          }
        }
      }
      return command;
    }

    private string commandName;
    public string CommandName
    {
      get
      {
        base.ReadPreamble();
        return this.commandName;
      }
      set
      {
        if (this.CommandName != value)
        {
          base.WritePreamble();
          this.commandName = value;
          base.WritePostscript();
        }
      }
    }

    #region Command
    public ICommand Command
    {
      get { return (ICommand)GetValue(CommandProperty); }
      set { SetValue(CommandProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Command.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty CommandProperty =
        DependencyProperty.Register("Command", typeof(ICommand), typeof(InteractiveCommand), new UIPropertyMetadata(null));
    #endregion
  }
}
